import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User } from 'src/user/entities/user.entity';
import { UserService } from 'src/user/user.service';
import { jwtConstants } from './constants';

const crypto = require('crypto-js');

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(
    username: string,
    password: string,
  ): Promise<{ error: boolean; message: string } | Omit<User, 'password'>> {
    const existUser = await this.userService.findByUsername(username);
    if (!existUser) {
      throw new BadRequestException( '用户不存在');
    }

    const isMatch =
      existUser.password === crypto.MD5(password).toString() ? true : false;

    if (!isMatch) {
      throw new BadRequestException( '密码不正确');
    }

    const { password: ignorePass, ...restUser } = existUser;

    return restUser;
  }

  async login(user: User) {
    const { password, ...restUser } = user;
    const payload = { ...restUser, sub: user.id };

    return {
      token: this.jwtService.sign(payload),
      user: restUser,
      expireIn: jwtConstants.expiresIn,
    };
  }
}
